<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="retireesPayrollDate" label="年月">
        <el-date-picker size="small"
                        v-model="queryParams.retireesPayrollDate"
                        type="month"
                        value-format="yyyy-MM"
                        @change="handleQuery"
                        placeholder="选择年月" style="width:250px"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="姓名" prop="nickName">
        <el-input
          prop="nickName"
          v-model="queryParams.nickName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
          style="width:250px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="auditStatus">
        <el-select clearable v-model="queryParams.auditStatus" placeholder="请选择审核状态" style="width:250px">
          <el-option
            v-for="item in auditStatusOptions"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['compensationManagement:retiresPayroll:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['compensationManagement:retiresPayroll:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['compensationManagement:retiresPayroll:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['compensationManagement:retiresPayroll:export']"
        >导出
        </el-button>
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入历史工资
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border stripe v-loading="loading" :data="retiresPayrollList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="工资表编号" align="center" prop="retireespayrollId"/>
      <el-table-column label="工号" align="center" prop="jobNumber"/>
      <el-table-column label="姓名" align="center" prop="nickName"/>
      <el-table-column label="工资年月" align="center" prop="retireespayrollDate" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.retireespayrollDate, '{y}-{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生成时间" width="180" align="center" prop="createTime"/>
      <el-table-column label="生活补贴" align="center" prop="livingallowance"/>
      <el-table-column label="住房改革补贴" align="center" prop="housingreformsubsidies"/>
      <el-table-column label="退休人员慰问金" align="center" prop="solatiumforretirees"/>
      <el-table-column label="其它浮动项合计" align="center" prop="floatTotal"/>
      <el-table-column label="合计" align="center" prop="retireesPayrollTotal"/>
      <el-table-column label="备注" align="center" prop="retireespayrollRemarks"/>
      <el-table-column label="状态" align="center" prop="auditStatus">
        <template slot-scope="{row}">
          <el-tag
            type="info"
            v-show="row.auditStatus===0"
          >
            未确定
          </el-tag>
          <el-tag
            type="success"
            v-show="row.auditStatus===1"
          > 确定
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="determinePayroll(scope.row)"
            v-hasPermi="['compensationManagement:setRetireeSubsidyItems:determiningPayrollRetirees']"
          >确定工资表
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['compensationManagement:retiresPayroll:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="viewModificationHistory(scope.row)"
            v-hasPermi="['compensationManagement:retiresPayrollLog:list']"
          >历史记录
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['compensationManagement:retiresPayroll:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改退休人员补贴工资对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="选择员工" prop="selectUser" v-show="form.retireespayrollId==null">
          <el-select v-model="form.selectUser" filterable remote style="width: 500px" reserve-keyword
                     placeholder="输入姓名进行选择" :remote-method="remoteMethod" @change="userChange()"
                     :loading="userObj.loading"
          >
            <el-option v-for="item in userObj.approverOptions" :key="item.value" :label="item.label"
                       :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工号" prop="jobNumber">
          <el-input v-model="form.jobNumber" :disabled="form.retireespayrollId!=null" @blur="jobnumberChange()"
                    placeholder="请输入工号"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="nickName">
          <el-input v-model="form.nickName" :disabled="form.retireespayrollId!=null" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="工资年月" prop="retireespayrollDate">
          <el-date-picker clearable
                          v-model="form.retireespayrollDate"
                          type="month"
                          value-format="yyyy-MM"
                          placeholder="请选择工资年月"
                          :disabled="form.retireespayrollId!=null"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="生活补贴" prop="livingallowance">
          <el-input-number v-model="form.livingallowance" @blur="incomeItemChange()" @change="incomeItemChange()"
                           :precision="2" controls-position="right" :min="0" :step="0.1"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="住房改革补贴" prop="housingreformsubsidies">
          <el-input-number v-model="form.housingreformsubsidies" @blur="incomeItemChange()" @change="incomeItemChange()"
                           :precision="2" controls-position="right" :min="0"
                           :step="0.1"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="退休人员慰问金" prop="solatiumforretirees">
          <el-input-number v-model="form.solatiumforretirees" @blur="incomeItemChange()" @change="incomeItemChange()"
                           :precision="2" controls-position="right" :min="0"
                           :step="0.1"
          ></el-input-number>
        </el-form-item>

        <el-form-item
          v-for="(domain, index) in form.floatingItems"
          :label="'浮动项目' + (index+1)"
          :prop="'floatingItems.' + index + '.subsidyprojectId'"
          :key="domain.subsidyprojectId"
        >
          <el-row :gutter="4">
            <el-col :span="5">
              <el-input v-model="domain.subsidyprojectName"></el-input>
            </el-col>
            <el-col :span="5">
              <el-input-number @blur="incomeItemChange()" @change="incomeItemChange()" placeholder="补贴项目金额"
                               :precision="2" v-model="domain.subsidyprojectMoney"
                               controls-position="right"
                               :min="0"
                               :step="0.1"
              ></el-input-number>
            </el-col>
          </el-row>
        </el-form-item>
        <el-row>
          <el-divider></el-divider>
          <el-col>
            <el-form-item label="实发数" prop="retireesPayrollTotal">
              <el-input-number :disabled="true" v-model="form.retireesPayrollTotal" :precision="2"
                               controls-position="right"
                               :min="0"
                               :step="0.1"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="retireespayrollRemarks">
          <el-input v-model="form.retireespayrollRemarks" type="textarea" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--历史记录弹出框-->
    <el-dialog :title="title" :visible.sync="openLog" width="850px">

      <div v-show="historyList.length!=0">
        <el-card class="box-card" v-for="(domain, index) in historyList">
          <div slot="header" class="clearfix">
            <span>操作记录{{ index + 1 }}</span>
          </div>
          <div v-for="(item, i) in domain.logInfoList">
            {{ domain.logInfoList[i] }}
          </div>
        </el-card>
      </div>

      <div v-show="historyList.length==0">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>操作记录</span>
          </div>
          <div>
            当前工资表无操作记录
          </div>
        </el-card>
      </div>

    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">

          <el-link type="primary" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">
          1.下载Excel模板<br/>
          2.设置【在编人员工号】整列的单元格格式为【文本】<br/>
          3.其中【在编人员工号】、【姓名】、【员工类型】、【工资年月】为必填项，其余工资数据如果为空，请填0
        </div>
        <div class="el-upload__tip" style="color:blue" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入结果对话框 -->
    <el-dialog :visible.sync="upload.result" width="400px">
      <div v-html="upload.resultMesg">
        {{ upload.resultMesg }}
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="upload.result = false">确 定</el-button>
        <el-button @click="upload.result = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRetiresPayroll,
  getRetiresPayroll,
  delRetiresPayroll,
  addRetiresPayroll,
  updateRetiresPayroll, getAllFloatingItems, determiningPayrollRetirees, getNickNameByJobNumber
} from '@/api/compensationManagement/retiresPayroll'
import { listSetRetireeSubsidyItems } from '@/api/compensationManagement/setRetireeSubsidyItems'
import { listStaffPayrollLog } from '@/api/compensationManagement/staffPayrollLog'
import { listRetiresPayrollLog } from '@/api/compensationManagement/retiresPayrollLog'
import { getPayrollInformationByJobNumber } from '@/api/compensationManagement/staffPayroll'
import { getToken } from '@/utils/auth'
import { debounce } from 'lodash'
import { getApproverNameByLike } from '@/api/out/workOvertime'

export default {
  name: 'RetiresPayroll',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 退休人员补贴工资表格数据
      retiresPayrollList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 历史记录
      openLog: false,
      // 历史记录标题
      logTitle: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        retireesPayrollDate: null
      },
      floatingItemsOption: [],
      // 表单参数
      form: {
        floatingItems: []
      },
      dynamicValidateForm: {
        domains: [{
          value: ''
        }],
        email: ''
      },
      // 表单校验
      rules: {
        jobNumber: [{ required: true, trigger: 'blur', message: '工号不能为空' }],
        retireespayrollDate: [{ required: true, trigger: 'change', message: '工资年月不能为空' }],
        nickName: [
          { required: true, trigger: 'blur', message: '姓名不能为空' }
        ],
        livingallowance: [{ required: true, trigger: 'blur', message: '生活补贴不能为空' }],
        housingreformsubsidies: [{ required: true, trigger: 'blur', message: '住房改革补贴不能为空' }],
        solatiumforretirees: [{ required: true, trigger: 'blur', message: '退休人员慰问金不能为空' }]
      },

      //全部补贴项目
      allSubsidyItemsOption: null,

      allFloatSubsidyItemsOption: [],
      //历史记录列表
      historyList: [],
      //strList
      strList: null,

      //审核状态
      auditStatusOptions: [
        {
          id: 1,
          value: '1',
          label: '确定'
        },
        {
          id: 2,
          value: '0',
          label: '未确定'
        }
      ],

      /* 工资表导入 */
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 是否显示弹出层（导入结果）
        result: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/compensationManagement/retiresPayroll/importData',
        //上传结果
        resultMesg: null
      },

      userObj: {
        approverOptions: [],
        loading: false
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询退休人员补贴工资列表 */
    getList() {
      this.loading = true
      listRetiresPayroll(this.queryParams).then(response => {
        this.retiresPayrollList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        retireespayrollId: null,
        jobNumber: null,
        nickName: null,
        retireespayrollDate: null,
        livingallowance: null,
        housingreformsubsidies: null,
        solatiumforretirees: null,
        retireesPayrollTotal: null,
        retireespayrollRemarks: null,
        floatingItems: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.retireespayrollId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      getAllFloatingItems().then(response => {
        this.floatingItemsOption = response.data
        if (this.floatingItemsOption != null) {
          this.form.floatingItems = this.floatingItemsOption
        }
      })
      listSetRetireeSubsidyItems().then(response => {
          this.allSubsidyItemsOption = response
          for (var i = 0; i < response.total; i++) {
            if (response.rows[i].subsidyprojectId == 1) {
              this.form.livingallowance = response.rows[i].subsidyprojectMoney
              this.form.retireesPayrollTotal += this.form.livingallowance * 100
            }
            if (response.rows[i].subsidyprojectId == 2) {
              this.form.housingreformsubsidies = response.rows[i].subsidyprojectMoney
              this.form.retireesPayrollTotal += this.form.housingreformsubsidies * 100
            }
            if (response.rows[i].subsidyprojectId == 3) {
              this.form.solatiumforretirees = response.rows[i].subsidyprojectMoney
              this.form.retireesPayrollTotal += this.form.solatiumforretirees * 100
            }
          }
          var sum = 0
          if (this.form.floatingItems != null) {
            for (var i in this.form.floatingItems) {
              sum = sum + this.form.floatingItems[i].subsidyprojectMoney * 100
            }
          }
          this.form.retireesPayrollTotal = (this.form.retireesPayrollTotal + sum) / 100
        }
      )
      this.title = '添加退休人员补贴工资'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const retireespayrollId = row.retireespayrollId || this.ids
      getRetiresPayroll(retireespayrollId).then(response => {
        this.form = response.data.fixedItems
        this.form.floatingItems = response.data.floatingItems
        this.open = true
        this.title = '修改退休人员补贴工资'
      })
    },
    /** 历史记录按钮操作 */
    viewModificationHistory(row) {
      const CompensationRetirespayrollLog = {
        retireesPayrollId: row.retireespayrollId
      }
      listRetiresPayrollLog(CompensationRetirespayrollLog).then(response => {
        this.historyList = response.rows
        this.openLog = true
        this.logTitle = '历史修改记录'
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.retireespayrollId != null) {
            updateRetiresPayroll(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addRetiresPayroll(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    }
    ,
    /** 删除按钮操作 */
    handleDelete(row) {
      const retireespayrollIds = row.retireespayrollId || this.ids
      this.$modal.confirm('是否确认删除退休人员补贴工资编号为"' + retireespayrollIds + '"的数据项？').then(function() {
        return delRetiresPayroll(retireespayrollIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    }
    ,
    /** 导出按钮操作 */
    handleExport() {
      this.download('compensationManagement/retiresPayroll/export', {
        ...this.queryParams
      }, `retiresPayroll_${new Date().getTime()}.xlsx`)
    }
    ,
    determinePayroll(row) {
      const retireespayrollIds = row.retireespayrollId || this.ids
      this.$modal.confirm('是否确定退休人员补贴工资编号为"' + retireespayrollIds + '"的补贴工资表？').then(function() {
        return determiningPayrollRetirees(row)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('确定成功')
      }).catch(() => {
      })
    }
    ,
    //重新计算应发工资、实发数
    incomeItemChange() {
      var sum = 0
      if (this.form.floatingItems != null) {
        for (var i in this.form.floatingItems) {
          sum = sum + this.form.floatingItems[i].subsidyprojectMoney * 100
        }
      }
      this.form.retireesPayrollTotal = (this.form.livingallowance * 100 + this.form.housingreformsubsidies * 100 + this.form.solatiumforretirees * 100 + sum) / 100
    },

    //工号输入框搜索
    jobnumberChange() {
      getNickNameByJobNumber(this.form.jobNumber).then(response => {
        //姓名
        this.form.nickName = response.msg
      })
    },

    /* 工资导入 */
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '历史工资导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('compensationManagement/retiresPayroll/importTemplate', {}, `退休人员补贴工资导入模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.upload.result = true
      this.upload.resultMesg = response.msg
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },

    remoteMethod: debounce(function(query) {
      if (query !== '') {
        this.userObj.loading = true
        //发送请求，根据用户姓名进行模糊查询
        getApproverNameByLike(query).then((res) => {
          this.userObj.loading = false
          this.userObj.approverOptions = res.data.map((item) => {
            return {
              value: `${item.jobNumber}`,
              label: `账号: ${item.userName}   姓名: ${item.nickName}  部门: ${item.deptName}`
            }
          })
        })
      } else {
        this.approverOptions = []
      }
    }, 500),
    userChange() {
      this.form.jobNumber = this.form.selectUser
      this.jobnumberChange()
    }
  }
}
</script>
<style>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 480px;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 110px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 1%;
  margin-bottom: 0;
  width: 100%;
}
</style>
